package edu.zut.util;

import java.sql.*;

/**
 * 针对JDBC操作数据的工具类，用于简化操作
 */
public class DBUtil {
    //将驱动名称、URL、USER、PASSWORD作为常量进行封装
    public static final String DRIVERNAME = "com.mysql.cj.jdbc.Driver";
    public static final String URL = "jdbc:mysql://127.0.0.1:3306/boot_crm?characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
    public static final String USER = "root";
    public static final String PASSWORD = "qwer1234";

    static {
        try {
            Class.forName(DRIVERNAME);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("驱动加载失败");
        }
    }
    static Connection coon = null;
    static PreparedStatement statement = null;
    static ResultSet rs = null;
    /**
     * 获取数据库连接
     * @return Connection
     */
    public static Connection getCoon(){
        try {
            coon = DriverManager.getConnection(URL,USER,PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return coon;
    }

    /**
     * 查询做统一封装
     * @param sql sql语句
     * @param objs sql中需要补充的参数
     * @return ResultSet 结果集
     */
    public static ResultSet query(String sql,Object... objs){
        coon = getCoon();
        try {
            statement = coon.prepareStatement(sql);
            //判断一下sql是否需要传参
            if (objs!= null && objs.length > 0){
                for (int i = 0; i < objs.length; i++) {
                    statement.setObject(i+1,objs[i]);
                }
            }
            rs = statement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    /**
     * 增删改做统一封装
     * @param sql 增删改sql
     * @param objs sql中需要的参数
     * @return int 增删改后受影响的行数
     */


    /**
     * 资源关闭
     */
    public static void free(){
        if (null != rs){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != statement){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != coon){
            try {
                coon.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }





}
